package controller

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/config"
	platformController "gitee.com/wangshh_123/cross-pay-go/src/controller/platform"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonpaymodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	ucommon "gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm"
)

// AdminController 管理员控制器
type AdminController struct {
	db                 *gorm.DB
	photonPayClient    *photonpay.PhotonPayClient
	hlPayClient        *hlPay.HlPayClient
	cardListController *platformController.CardListController
}

// NewAdminController 创建管理员控制器实例
func NewAdminController(db *gorm.DB, photonPayClient *photonpay.PhotonPayClient, hlPayClient *hlPay.HlPayClient) *AdminController {
	return &AdminController{
		db:                 db,
		photonPayClient:    photonPayClient,
		hlPayClient:        hlPayClient,
		cardListController: platformController.NewCardListController(photonPayClient, hlPayClient, db),
	}
}

// CreateRole 创建新角色
func (c *AdminController) CreateRole(ctx *gin.Context) {
	var role models.Role
	if err := ctx.ShouldBindJSON(&role); err != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	if err := c.db.Create(&role).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "INTERNAL_ERROR", err)
		return
	}

	ucommon.Success(ctx, role)
}

// GetRoles 获取所有角色列表
func (c *AdminController) GetRoles(ctx *gin.Context) {
	var roles []models.Role
	result := c.db.Find(&roles)
	if result.Error != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "error", fmt.Errorf("database query failed: %v", result.Error))
		return
	}

	// 如果没有找到任何角色，返回空数组而不是错误
	if result.RowsAffected == 0 {
		ucommon.Success(ctx, []models.Role{})
		return
	}

	// 确保每个角色的权限字段都被正确初始化
	for i := range roles {
		if roles[i].Permissions == nil {
			roles[i].Permissions = make(models.PermissionsMap)
		}
	}

	ucommon.Success(ctx, roles)
}

// UpdateRole 更新现有角色
func (c *AdminController) UpdateRole(ctx *gin.Context) {
	id := ctx.Param("id")
	var role models.Role
	if err := ctx.ShouldBindJSON(&role); err != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	if err := c.db.Model(&models.Role{}).Where("id = ?", id).Updates(role).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "INTERNAL_ERROR", err)
		return
	}

	ucommon.Success(ctx, role)
}

// DeleteRole 删除角色
func (c *AdminController) DeleteRole(ctx *gin.Context) {
	id := ctx.Param("id")
	if err := c.db.Delete(&models.Role{}, id).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "INTERNAL_ERROR", err)
		return
	}

	ucommon.Success(ctx, nil)
}

// AssignRoleToUser 为用户分配角色
func (c *AdminController) AssignRoleToUser(ctx *gin.Context) {
	var userRole models.UserRole
	if err := ctx.ShouldBindJSON(&userRole); err != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 使用 UserService 创建用户角色关联
	userService := service.NewUserService()
	if err := userService.CreateUserRole(&userRole); err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "create_user_role_failed", err)
		return
	}

	ucommon.Success(ctx, userRole)
}

// RemoveRoleFromUser 移除用户的角色
func (c *AdminController) RemoveRoleFromUser(ctx *gin.Context) {
	userID := ctx.Param("userId")
	roleID := ctx.Param("roleId")

	if err := c.db.Where("user_id = ? AND role_id = ?", userID, roleID).Delete(&models.UserRole{}).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "INTERNAL_ERROR", err)
		return
	}

	ucommon.Success(ctx, nil)
}

// GetUserRoles 获取指定用户的所有角色
func (c *AdminController) GetUserRoles(ctx *gin.Context) {
	userID := ctx.Param("userId")
	var roles []models.Role

	if err := c.db.Joins("JOIN user_roles ON user_roles.role_id = roles.id").
		Where("user_roles.user_id = ?", userID).
		Find(&roles).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "INTERNAL_ERROR", err)
		return
	}

	ucommon.Success(ctx, roles)
}

// 分账户锁map
var accountLocks sync.Map // key: matrix_account, value: *sync.Mutex

// 主账户锁map
var masterAccountLocks sync.Map // key: account_name, value: *sync.Mutex
func getMasterAccountLock(account string) *sync.Mutex {
	lock, _ := masterAccountLocks.LoadOrStore(account, &sync.Mutex{})
	return lock.(*sync.Mutex)
}

func getAccountLock(account string) *sync.Mutex {
	lock, _ := accountLocks.LoadOrStore(account, &sync.Mutex{})
	return lock.(*sync.Mutex)
}

// AdminMatrixTransfer 管理员执行矩阵转账
func (c *AdminController) AdminMatrixTransfer(ctx *gin.Context) {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		ucommon.Error(ctx, http.StatusUnauthorized, "UNAUTHORIZED", nil)
		return
	}

	// 检查用户是否有管理员权限和转账权限
	var role models.Role
	if err := c.db.Joins("JOIN user_roles ON user_roles.role_id = roles.id").
		Where("user_roles.user_id = ? AND roles.status = 1", userID).
		First(&role).Error; err != nil {
		ucommon.Error(ctx, http.StatusForbidden, "NO_PERMISSION", err)
		return
	}

	// 检查是否有管理员权限
	if role.Permissions == nil {
		role.Permissions = make(models.PermissionsMap)
	}
	if !role.Permissions["admin:access"] {
		ucommon.Error(ctx, http.StatusForbidden, "NO_ADMIN_PERMISSION", nil)
		return
	}

	// 检查是否有矩阵转账权限
	if !role.Permissions["matrix_transfer"] {
		ucommon.Error(ctx, http.StatusForbidden, "NO_MATRIX_TRANSFER_PERMISSION", nil)
		return
	}

	var req struct {
		Currency        string `json:"currency" binding:"required"`
		PlatformAccount string `json:"platformAccount" binding:"required"`
		TransferAmount  string `json:"transferAmount" binding:"required"`
		TransferType    string `json:"transferType" binding:"required,oneof=transfer_in transfer_out"`
		Remark          string `json:"remark"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", fmt.Errorf("参数验证失败: %v", err))
		return
	}

	// 验证转账金额
	amount, err := strconv.ParseFloat(req.TransferAmount, 64)
	if err != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_AMOUNT_FORMAT", fmt.Errorf("转账金额格式错误: %v", err))
		return
	}
	if amount <= 0 {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_AMOUNT", fmt.Errorf("转账金额必须大于0"))
		return
	}

	// 获取矩阵账户信息
	var matrixAccount models.UserMatrixAccount
	if err := c.db.Where("matrix_account = ? AND status = 'active'", req.PlatformAccount).First(&matrixAccount).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			ucommon.Error(ctx, http.StatusBadRequest, "MATRIX_ACCOUNT_NOT_FOUND", fmt.Errorf("未找到有效的矩阵账户: %s", req.PlatformAccount))
		} else {
			ucommon.Error(ctx, http.StatusInternalServerError, "DATABASE_ERROR", err)
		}
		return
	}

	// 新增：不允许对子账号转账
	if matrixAccount.ParentMatrixAccountID != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "CANNOT_TRANSFER_TO_SUB_ACCOUNT", fmt.Errorf("不允许对子账号转账"))
		return
	}

	// 构造请求体
	bodyBytes, err := json.Marshal(map[string]interface{}{
		"transferAmount": req.TransferAmount,
		"currency":       req.Currency,
		"matrixAccount":  req.PlatformAccount,
		"transferType":   req.TransferType,
	})
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "JSON_FORMAT_ERROR", err)
		return
	}

	// 创建 PhotonPay 客户端
	client := c.photonPayClient

	// 1. 先插入一条 processing 状态的转账记录
	tx := c.db.Begin()
	if tx.Error != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "TRANSACTION_START_FAILED", tx.Error)
		return
	}
	transferRecord := models.AdminTransferRecord{
		AdminID:         userID.(int64),
		Platform:        "photonpay",
		PlatformAccount: req.PlatformAccount,
		TransferAmount:  amount,
		Currency:        req.Currency,
		TransferType:    req.TransferType,
		Status:          "processing",
		Remark:          req.Remark,
	}
	if err := tx.Create(&transferRecord).Error; err != nil {
		tx.Rollback()
		ucommon.Error(ctx, http.StatusInternalServerError, "CREATE_TRANSFER_RECORD_FAILED", err)
		return
	}
	tx.Commit()

	// 调用第三方接口前，暂停2分钟，便于观察数据库记录
	// time.Sleep(1 * time.Minute)

	// 2. 调用第三方接口
	result, err := services.MatrixTransfer(ctx.Request.Context(), client, bodyBytes)

	// 3. 开启新事务，更新转账记录
	tx = c.db.Begin()
	if tx.Error != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "TRANSACTION_START_FAILED", tx.Error)
		return
	}

	if err != nil {
		tx.Model(&models.AdminTransferRecord{}).Where("id = ?", transferRecord.ID).
			Updates(map[string]interface{}{
				"Status":       "failed",
				"ErrorMessage": err.Error(),
			})
		tx.Commit()
		ucommon.Error(ctx, http.StatusInternalServerError, "TRANSFER_FAILED", err)
		return
	}

	resultMap := make(map[string]interface{})
	err = json.Unmarshal(result, &resultMap)
	if err != nil {
		tx.Model(&models.AdminTransferRecord{}).Where("id = ?", transferRecord.ID).
			Updates(map[string]interface{}{
				"Status":       "failed",
				"ErrorMessage": err.Error(),
			})
		tx.Commit()
		ucommon.Error(ctx, http.StatusInternalServerError, "PARSE_RESULT_FAILED", err)
		return
	}

	code, ok := resultMap["code"].(string)
	if !ok || code != "0000" {
		errMsg := fmt.Sprintf("code: %v, msg: %v", code, resultMap["msg"])
		tx.Model(&models.AdminTransferRecord{}).Where("id = ?", transferRecord.ID).
			Updates(map[string]interface{}{
				"Status":       "failed",
				"ErrorMessage": errMsg,
			})
		tx.Commit()
		ucommon.Error(ctx, http.StatusInternalServerError, "TRANSFER_FAILED", fmt.Errorf(errMsg))
		return
	}

	// 获取交易ID
	var transactionID string
	if data, ok := resultMap["data"]; ok {
		switch v := data.(type) {
		case map[string]interface{}:
			if id, ok := v["transactionId"].(string); ok {
				transactionID = id
			}
		case string:
			transactionID = v
		}
	}

	// 更新为成功
	if dbRes := tx.Model(&models.AdminTransferRecord{}).Where("id = ?", transferRecord.ID).
		Updates(map[string]interface{}{
			"Status":        "success",
			"TransactionID": transactionID,
			"ErrorMessage":  "",
		}); dbRes.Error != nil {
		tx.Rollback()
		ucommon.Error(ctx, http.StatusInternalServerError, "CREATE_TRANSFER_RECORD_FAILED", dbRes.Error)
		return
	}

	// 更新本地余额等后续处理（原有逻辑）
	amountDecimal := decimal.NewFromFloat(amount)
	var updateAmount decimal.Decimal
	if req.TransferType == "transfer_in" {
		updateAmount = amountDecimal
	} else {
		updateAmount = amountDecimal.Neg()
	}

	var userRole models.UserRole
	if err := tx.Where("user_id = ?", matrixAccount.UserID).First(&userRole).Error; err != nil {
		tx.Rollback()
		ucommon.Error(ctx, http.StatusInternalServerError, "GET_USER_ROLE_FAILED", err)
		return
	}

	switch userRole.RoleID {
	case 3: // 普通用户、管理员、主账号都使用主账号表
		if err := tx.Model(&models.MasterAccount{}).
			Where("user_id = ?", matrixAccount.UserID).
			Update("balance", gorm.Expr("balance + ?", updateAmount)).Error; err != nil {
			tx.Rollback()
			ucommon.Error(ctx, http.StatusInternalServerError, "UPDATE_MASTER_ACCOUNT_BALANCE_FAILED", err)
			return
		}
	case 5: // 子账号
		if err := tx.Model(&models.SubAccount{}).
			Where("user_id = ?", matrixAccount.UserID).
			Update("balance", gorm.Expr("balance + ?", updateAmount)).Error; err != nil {
			tx.Rollback()
			ucommon.Error(ctx, http.StatusInternalServerError, "UPDATE_SUB_ACCOUNT_BALANCE_FAILED", err)
			return
		}
	default:
		// 对于其他角色，也使用主账号表（保持向后兼容）
		if err := tx.Model(&models.MasterAccount{}).
			Where("user_id = ?", matrixAccount.UserID).
			Update("balance", gorm.Expr("balance + ?", updateAmount)).Error; err != nil {
			tx.Rollback()
			ucommon.Error(ctx, http.StatusInternalServerError, "UPDATE_MASTER_ACCOUNT_BALANCE_FAILED", err)
			return
		}
	}

	if err := tx.Model(&models.UserMatrixAccount{}).
		Where("matrix_account = ? AND status = 'active'", req.PlatformAccount).
		Update("total_transfer_amount", gorm.Expr("total_transfer_amount + ?", updateAmount)).Error; err != nil {
		tx.Rollback()
		ucommon.Error(ctx, http.StatusInternalServerError, "UPDATE_TRANSFER_AMOUNT_FAILED", err)
		return
	}

	if err := tx.Commit().Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "TRANSACTION_COMMIT_FAILED", err)
		return
	}

	// 生成带Matrix_account的短交易流水号（不超过32位）
	accountSuffix := req.PlatformAccount
	if len(accountSuffix) > 8 {
		accountSuffix = accountSuffix[len(accountSuffix)-8:]
	}
	timestamp := time.Now().UnixNano() / 1e6 // 毫秒
	randomNum := rand.Intn(10000)            // 4位随机数
	transactionID = fmt.Sprintf("%s%x%04d", accountSuffix, timestamp, randomNum)
	if len(transactionID) > 32 {
		transactionID = transactionID[:32]
	}

	// 创建通知
	notificationService := service.NewNotificationService()

	// 根据转账类型设置标题和操作类型
	var title, operationType string
	switch req.TransferType {
	case "transfer_in":
		title = "资金转入通知"
		operationType = "转入"
	case "transfer_out":
		title = "资金转出通知"
		operationType = "转出"
	case "refund":
		title = "资金退还通知"
		operationType = "退还"
	default:
		title = "资金变动通知"
		operationType = "变动"
	}

	notification := &models.Notification{
		UserID: matrixAccount.UserID,
		TypeID: 3, // 使用type_id 3
		Title:  title,
		Content: fmt.Sprintf("您的账户(%s)%s%.2f%s，交易流水号：%s",
			req.PlatformAccount,
			operationType,
			amount,
			req.Currency,
			transactionID,
		),
		Data:   models.JSON(fmt.Sprintf(`{"Matrix_account":"%s","transaction_ID":"%s"}`, req.PlatformAccount, transactionID)),
		Status: "UNREAD",
	}
	if err := notificationService.CreateNotification(ctx, notification); err != nil {
		fmt.Printf("创建通知失败: %v\n", err)
	}

	ucommon.Success(ctx, resultMap["data"])
}

// GetMatrixAccount 获取单个矩阵账户信息
func (c *AdminController) GetMatrixAccount(ctx *gin.Context) {
	// 获取账户ID
	accountID := ctx.Param("id")
	if accountID == "" {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", fmt.Errorf("账户ID不能为空"))
		return
	}

	// 查询账户信息，关联用户表
	var account models.UserMatrixAccount
	if err := c.db.Preload("User", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, username, phone, email")
	}).First(&account, accountID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			ucommon.Error(ctx, http.StatusNotFound, "ACCOUNT_NOT_FOUND", fmt.Errorf("未找到账户信息"))
		} else {
			ucommon.Error(ctx, http.StatusInternalServerError, "DATABASE_ERROR", err)
		}
		return
	}

	ucommon.Success(ctx, account)
}

// GetMatrixAccounts 获取矩阵账户列表
func (c *AdminController) GetMatrixAccounts(ctx *gin.Context) {
	// 获取查询参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))
	status := ctx.Query("status")
	matrixAccount := ctx.Query("matrix_account")
	userIDStr := ctx.Query("user_id")
	// 获取用户信息查询参数
	userKeyword := ctx.Query("user_keyword") // 支持姓名、邮箱、手机号模糊搜索

	// 构建查询，排除角色为1或6的用户账户
	query := c.db.Model(&models.UserMatrixAccount{}).
		Joins("JOIN users ON user_matrix_accounts.user_id = users.id").
		Joins("LEFT JOIN user_roles ON users.id = user_roles.user_id").
		Joins("LEFT JOIN roles ON user_roles.role_id = roles.id").
		Where("(roles.id IS NULL OR (roles.id != 1 AND roles.id != 6))")

	// 添加筛选条件
	if status != "" {
		query = query.Where("user_matrix_accounts.status = ?", status)
	}
	if matrixAccount != "" {
		query = query.Where("user_matrix_accounts.matrix_account LIKE ?", "%"+matrixAccount+"%")
	}
	if userIDStr != "" {
		query = query.Where("user_matrix_accounts.user_id = ?", userIDStr)
	}
	// 添加用户信息模糊搜索
	if userKeyword != "" {
		query = query.Where("(users.name LIKE ? OR users.email LIKE ? OR users.phone LIKE ?)",
			"%"+userKeyword+"%", "%"+userKeyword+"%", "%"+userKeyword+"%")
	}

	// 获取总记录数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "COUNT_ERROR", err)
		return
	}

	// 分页查询，关联用户表
	var accounts []models.UserMatrixAccount
	if err := query.Preload("User", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, username, phone, email, name")
	}).Offset((page - 1) * pageSize).
		Limit(pageSize).
		Order("user_matrix_accounts.created_at DESC").
		Find(&accounts).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "QUERY_ERROR", err)
		return
	}

	// 返回结果
	ucommon.Success(ctx, gin.H{
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
		"list":     accounts,
	})
}

// GetAccountList 获取金额账户列表
func (c *AdminController) GetAccountList(ctx *gin.Context) {
	// 获取查询参数
	params := photonpaymodels.AccountListQueryParams{
		AccountNo:     ctx.Query("account_no"),
		MemberID:      ctx.Query("member_id"),
		MatrixAccount: ctx.Query("matrix_account"),
	}

	// 创建 PhotonPay 客户端
	client := c.photonPayClient

	// 调用 PhotonPay 服务获取账户列表
	result, err := services.GetAccountList(ctx.Request.Context(), client, params)
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "GET_ACCOUNT_LIST_FAILED", err)
		return
	}

	ucommon.Success(ctx, result.Data)
}

// GetAdminTransferRecords 获取管理员转账记录列表
func (c *AdminController) GetAdminTransferRecords(ctx *gin.Context) {
	// 获取查询参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))
	status := ctx.Query("status")
	platform := ctx.Query("platform")
	platformAccount := ctx.Query("platform_account")
	currency := ctx.Query("currency")
	transferType := ctx.Query("transfer_type")
	startTime := ctx.Query("start_time")
	endTime := ctx.Query("end_time")

	// 新增用户信息筛选参数
	userEmail := ctx.Query("user_email")
	userPhone := ctx.Query("user_phone")
	userName := ctx.Query("user_name")

	// 构建查询，关联用户矩阵账户和用户信息
	query := c.db.Model(&models.AdminTransferRecord{}).
		Joins("LEFT JOIN user_matrix_accounts ON admin_transfer_records.platform_account = user_matrix_accounts.matrix_account").
		Joins("LEFT JOIN users ON user_matrix_accounts.user_id = users.id")

	// 添加筛选条件
	if status != "" {
		query = query.Where("admin_transfer_records.status = ?", status)
	}
	if platform != "" {
		query = query.Where("admin_transfer_records.platform = ?", platform)
	}
	if platformAccount != "" {
		query = query.Where("admin_transfer_records.platform_account LIKE ?", "%"+platformAccount+"%")
	}
	if currency != "" {
		query = query.Where("admin_transfer_records.currency = ?", currency)
	}
	if transferType != "" {
		query = query.Where("admin_transfer_records.transfer_type = ?", transferType)
	}
	if startTime != "" {
		query = query.Where("admin_transfer_records.created_at >= ?", startTime)
	}
	if endTime != "" {
		query = query.Where("admin_transfer_records.created_at <= ?", endTime)
	}

	// 添加用户信息筛选条件
	if userEmail != "" {
		query = query.Where("users.email LIKE ?", "%"+userEmail+"%")
	}
	if userPhone != "" {
		query = query.Where("users.phone LIKE ?", "%"+userPhone+"%")
	}
	if userName != "" {
		query = query.Where("users.name LIKE ?", "%"+userName+"%")
	}

	// 获取总记录数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "COUNT_ERROR", err)
		return
	}

	// 分页查询，包含用户信息
	var records []models.AdminTransferRecord
	if err := query.Preload("Admin", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, username, phone, email")
	}).Preload("UserMatrixAccount", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, user_id, matrix_account, matrix_account_name, platform_type, status")
	}).Preload("UserMatrixAccount.User", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, username, phone, email, name")
	}).Offset((page - 1) * pageSize).
		Limit(pageSize).
		Order("admin_transfer_records.created_at DESC").
		Find(&records).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "QUERY_ERROR", err)
		return
	}

	// 返回结果
	ucommon.Success(ctx, gin.H{
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
		"list":     records,
	})
}

// GetCardListByMatrixAccount 根据matrix账户获取卡列表
func (c *AdminController) GetCardListByMatrixAccount(ctx *gin.Context) {
	fmt.Printf("[AdminController] ===== 开始处理管理员卡列表查询 =====\n")

	// 获取查询参数
	matrixAccount := ctx.Query("matrix_account")
	if matrixAccount == "" {
		ucommon.Error(ctx, http.StatusBadRequest, "MATRIX_ACCOUNT_REQUIRED", fmt.Errorf("matrix账户不能为空"))
		return
	}

	fmt.Printf("[AdminController] 查询matrix账户: %s\n", matrixAccount)

	// 根据matrix账户获取用户信息和平台类型
	var userMatrixAccount models.UserMatrixAccount
	if err := c.db.Where("matrix_account = ? AND status = 'active'", matrixAccount).First(&userMatrixAccount).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			ucommon.Error(ctx, http.StatusNotFound, "MATRIX_ACCOUNT_NOT_FOUND", fmt.Errorf("未找到有效的矩阵账户: %s", matrixAccount))
		} else {
			ucommon.Error(ctx, http.StatusInternalServerError, "DATABASE_ERROR", err)
		}
		return
	}

	fmt.Printf("[AdminController] 获取到用户矩阵账户信息: PlatformType=%s, UserID=%d\n",
		userMatrixAccount.PlatformType, userMatrixAccount.UserID)

	// 设置平台信息到上下文中，供 CardListController 使用
	platformInfo := &middleware.PlatformInfo{
		PlatformType:  userMatrixAccount.PlatformType,
		MatrixAccount: userMatrixAccount.MatrixAccount,
		Status:        userMatrixAccount.Status,
	}
	ctx.Set("platform_info", platformInfo)
	ctx.Set("matrix_account_info", &userMatrixAccount)

	// 设置用户信息到上下文中
	claims := &auth.Claims{
		UserID: userMatrixAccount.UserID,
		RoleID: 1, // 管理员角色
	}
	ctx.Set("claims", claims)

	// 直接调用 CardListController 的 GetCardList 方法
	c.cardListController.GetCardList(ctx)

	fmt.Printf("[AdminController] ===== 管理员卡列表查询处理完成 =====\n")
}

// GetAccountBalanceByMatrixAccount 根据matrix账户获取账户资金
func (c *AdminController) GetAccountBalanceByMatrixAccount(ctx *gin.Context) {
	// 获取查询参数
	matrixAccount := ctx.Query("matrix_account")
	if matrixAccount == "" {
		ucommon.Error(ctx, http.StatusBadRequest, "MATRIX_ACCOUNT_REQUIRED", fmt.Errorf("matrix账户不能为空"))
		return
	}

	// 构建查询参数
	params := photonpaymodels.AccountListQueryParams{
		AccountNo:     ctx.Query("accountNo"),
		MemberID:      ctx.Query("memberId"),
		MatrixAccount: matrixAccount,
	}
	fmt.Printf("查询参数: %+v\n", params)

	// 获取 PhotonPay 客户端
	client := c.photonPayClient

	// 调用服务获取账户列表
	result, err := services.GetAccountList(ctx.Request.Context(), client, params)
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "GET_ACCOUNT_LIST_FAILED", err)
		return
	}

	// 返回成功响应
	ucommon.Success(ctx, result)
}

// GetAccountHistoryByMatrixAccount 根据matrix账户获取交易明细
func (c *AdminController) GetAccountHistoryByMatrixAccount(ctx *gin.Context) {
	// 获取查询参数
	matrixAccount := ctx.Query("matrixAccount")
	if matrixAccount == "" {
		ucommon.Error(ctx, http.StatusBadRequest, "MATRIX_ACCOUNT_REQUIRED", fmt.Errorf("matrix账户不能为空"))
		return
	}

	// 获取分页参数，支持 pageIndex/pageSize
	page, pageSize := common.GetPaginationParams(ctx)

	params := photonpaymodels.VccTradeOrderQueryParams{
		PageIndex:       page,
		PageSize:        pageSize,
		MatrixAccount:   matrixAccount,
		CardID:          ctx.Query("cardId"),
		CardType:        ctx.Query("cardType"),
		RequestID:       ctx.Query("requestId"),
		TransactionID:   ctx.Query("transactionId"),
		Status:          ctx.Query("status"),
		TransactionType: ctx.Query("transactionType"),
		CreatedAtStart:  ctx.Query("createdAtStart"),
		CreatedAtEnd:    ctx.Query("createdAtEnd"),
		CardNickname:    ctx.Query("cardNickname"),
	}

	result, err := services.GetVccTradeOrderList(ctx.Request.Context(), c.photonPayClient, params)
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_vcc_trade_failed", err)
		return
	}

	ucommon.Success(ctx, result)
}

// 极简转账接口，只调用 MatrixTransfer
func (c *AdminController) AdminMatrixTransferTT(ctx *gin.Context) {
	var req struct {
		Currency        string `json:"currency"`
		PlatformAccount string `json:"platformAccount"`
		TransferAmount  string `json:"transferAmount"`
		TransferType    string `json:"transferType"`
		Remark          string `json:"remark"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	bodyBytes, err := json.Marshal(map[string]interface{}{
		"transferAmount": req.TransferAmount,
		"currency":       req.Currency,
		"matrixAccount":  req.PlatformAccount,
		"transferType":   req.TransferType,
	})
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "JSON_FORMAT_ERROR", err)
		return
	}

	client := c.photonPayClient
	result, err := services.MatrixTransfer(ctx.Request.Context(), client, bodyBytes)
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "TRANSFER_FAILED", err)
		return
	}

	ucommon.Success(ctx, string(result))
}

// 极简Matrix账户列表接口，直接返回三方接口原始JSON响应
func (c *AdminController) GetMatrixAccountListRaw(ctx *gin.Context) {
	matrixAccount := ctx.Query("matrixAccount")
	pageIndex := ctx.DefaultQuery("pageIndex", "1")
	pageSize := ctx.DefaultQuery("pageSize", "1024")
	createdAtStart := ctx.Query("createdAtStart")
	createdAtEnd := ctx.Query("createdAtEnd")

	query := url.Values{}
	query.Set("pageIndex", pageIndex)
	query.Set("pageSize", pageSize)
	if matrixAccount != "" {
		query.Set("matrixAccount", matrixAccount)
	}
	if createdAtStart != "" {
		query.Set("createdAtStart", createdAtStart)
	}
	if createdAtEnd != "" {
		query.Set("createdAtEnd", createdAtEnd)
	}

	path := "/matrix/openApi/v4/getPageMatrixAccountInfo"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	client := c.photonPayClient
	resp, err := client.Get(ctx.Request.Context(), path)
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "GET_MATRIX_ACCOUNT_LIST_FAILED", err)
		return
	}

	ctx.Data(http.StatusOK, "application/json", resp)
}

// GetStatistics 获取统计数据（包含开卡、转账和用户统计）
func (c *AdminController) GetStatistics(ctx *gin.Context) {
	// 获取查询参数
	startDate := ctx.DefaultQuery("start_date", time.Now().AddDate(0, 0, -30).Format("2006-01-02"))
	endDate := ctx.DefaultQuery("end_date", time.Now().Format("2006-01-02"))
	platform := ctx.Query("platform")
	currency := ctx.Query("currency")

	// 1. 用户统计
	// 获取总用户数（不包括已删除的用户）
	var totalUsers int64
	if err := c.db.Model(&models.User{}).Where("is_deleted = ?", 0).Count(&totalUsers).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 获取每日新增用户数
	type UserDailyStats struct {
		Date  string `json:"date"`
		Count int64  `json:"count"`
	}
	var userDailyStats []UserDailyStats

	userSQL := `
		SELECT DATE(created_at) as date, COUNT(*) as count 
		FROM users 
		WHERE created_at BETWEEN ? AND ? AND is_deleted = 0
		GROUP BY DATE(created_at) 
		ORDER BY date
	`
	if err := c.db.Raw(userSQL, startDate, endDate+" 23:59:59").Scan(&userDailyStats).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 获取用户状态统计
	type UserStatusStats struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	var userStatusStats []UserStatusStats

	userStatusSQL := `
		SELECT 
			CASE 
				WHEN status = 1 THEN 'active'
				WHEN status = 0 THEN 'disabled'
			END as status,
			COUNT(*) as count
		FROM users 
		WHERE is_deleted = 0
		GROUP BY status
	`
	if err := c.db.Raw(userStatusSQL).Scan(&userStatusStats).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 2. 开卡统计
	// 构建基础查询
	cardQuery := c.db.Model(&models.UserCard{})

	// 添加平台筛选条件
	if platform != "" {
		cardQuery = cardQuery.Where("platform = ?", platform)
	}

	// 获取总开卡数
	var totalCards int64
	if err := cardQuery.Count(&totalCards).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 获取每日开卡数
	type CardDailyStats struct {
		Date  string `json:"date"`
		Count int64  `json:"count"`
	}
	var cardDailyStats []CardDailyStats

	// 使用原生SQL进行日期统计
	cardSQL := `
		SELECT DATE(created_at) as date, COUNT(*) as count 
		FROM user_cards 
		WHERE created_at BETWEEN ? AND ?
	`
	cardArgs := []interface{}{startDate, endDate + " 23:59:59"}
	if platform != "" {
		cardSQL += " AND platform = ?"
		cardArgs = append(cardArgs, platform)
	}
	cardSQL += " GROUP BY DATE(created_at) ORDER BY date"

	if err := c.db.Raw(cardSQL, cardArgs...).Scan(&cardDailyStats).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 获取各状态卡数量
	type CardStatusStats struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	var cardStatusStats []CardStatusStats

	cardStatusSQL := `
		SELECT card_status as status, COUNT(*) as count 
		FROM user_cards 
	`
	cardStatusArgs := []interface{}{}
	if platform != "" {
		cardStatusSQL += " WHERE platform = ?"
		cardStatusArgs = append(cardStatusArgs, platform)
	}
	cardStatusSQL += " GROUP BY card_status"

	if err := c.db.Raw(cardStatusSQL, cardStatusArgs...).Scan(&cardStatusStats).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 3. 转账统计
	// 构建基础查询
	transferQuery := c.db.Model(&models.AdminTransferRecord{})

	// 添加筛选条件
	if platform != "" {
		transferQuery = transferQuery.Where("platform = ?", platform)
	}
	if currency != "" {
		transferQuery = transferQuery.Where("currency = ?", currency)
	}

	// 获取总转入金额
	var totalTransferIn float64
	if err := transferQuery.Where("transfer_type = ? AND status = ?", "transfer_in", "success").
		Select("COALESCE(SUM(transfer_amount), 0)").
		Scan(&totalTransferIn).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 获取总转出金额
	var totalTransferOut float64
	if err := transferQuery.Where("transfer_type = ? AND status = ?", "transfer_out", "success").
		Select("COALESCE(SUM(transfer_amount), 0)").
		Scan(&totalTransferOut).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 获取每日转账金额
	type TransferDailyStats struct {
		Date          string  `json:"date"`
		TransferIn    float64 `json:"transfer_in"`
		TransferOut   float64 `json:"transfer_out"`
		NetAmount     float64 `json:"net_amount"`
		TransferCount int64   `json:"transfer_count"`
	}
	var transferDailyStats []TransferDailyStats

	// 使用原生SQL进行日期统计
	transferSQL := `
		SELECT 
			DATE(created_at) as date,
			COALESCE(SUM(CASE WHEN transfer_type = 'transfer_in' AND status = 'success' THEN transfer_amount ELSE 0 END), 0) as transfer_in,
			COALESCE(SUM(CASE WHEN transfer_type = 'transfer_out' AND status = 'success' THEN transfer_amount ELSE 0 END), 0) as transfer_out,
			COUNT(*) as transfer_count
		FROM admin_transfer_records 
		WHERE created_at BETWEEN ? AND ?
	`
	transferArgs := []interface{}{startDate, endDate + " 23:59:59"}
	if platform != "" {
		transferSQL += " AND platform = ?"
		transferArgs = append(transferArgs, platform)
	}
	if currency != "" {
		transferSQL += " AND currency = ?"
		transferArgs = append(transferArgs, currency)
	}
	transferSQL += " GROUP BY DATE(created_at) ORDER BY date"

	if err := c.db.Raw(transferSQL, transferArgs...).Scan(&transferDailyStats).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 计算每日净额
	for i := range transferDailyStats {
		transferDailyStats[i].NetAmount = transferDailyStats[i].TransferIn - transferDailyStats[i].TransferOut
	}

	// 获取各状态转账数量
	type TransferStatusStats struct {
		Status string  `json:"status"`
		Count  int64   `json:"count"`
		Amount float64 `json:"amount"`
	}
	var transferStatusStats []TransferStatusStats

	transferStatusSQL := `
		SELECT 
			status,
			COUNT(*) as count,
			COALESCE(SUM(transfer_amount), 0) as amount
		FROM admin_transfer_records 
	`
	transferStatusArgs := []interface{}{}
	if platform != "" {
		transferStatusSQL += " WHERE platform = ?"
		transferStatusArgs = append(transferStatusArgs, platform)
	}
	if currency != "" {
		if len(transferStatusArgs) > 0 {
			transferStatusSQL += " AND"
		} else {
			transferStatusSQL += " WHERE"
		}
		transferStatusSQL += " currency = ?"
		transferStatusArgs = append(transferStatusArgs, currency)
	}
	transferStatusSQL += " GROUP BY status"

	if err := c.db.Raw(transferStatusSQL, transferStatusArgs...).Scan(&transferStatusStats).Error; err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_statistics_failed", err)
		return
	}

	// 返回结果
	ucommon.Success(ctx, gin.H{
		"user_statistics": gin.H{
			"total_users":  totalUsers,
			"daily_stats":  userDailyStats,
			"status_stats": userStatusStats,
		},
		"card_statistics": gin.H{
			"total_cards":  totalCards,
			"daily_stats":  cardDailyStats,
			"status_stats": cardStatusStats,
		},
		"transfer_statistics": gin.H{
			"total_transfer_in":  totalTransferIn,
			"total_transfer_out": totalTransferOut,
			"net_amount":         totalTransferIn - totalTransferOut,
			"daily_stats":        transferDailyStats,
			"status_stats":       transferStatusStats,
		},
		"query_params": gin.H{
			"start_date": startDate,
			"end_date":   endDate,
			"platform":   platform,
			"currency":   currency,
		},
	})
}

// ReadFilesByDates 根据日期列表读取 trades_YYYY-MM-DD.xlsx 文件内容
func (c *AdminController) ReadFilesByDates(ctx *gin.Context) {
	basePath := config.GlobalConfig.FilePath
	if basePath == "" {
		ucommon.Error(ctx, http.StatusInternalServerError, "CONFIG_ERROR", fmt.Errorf("文件路径配置为空"))
		return
	}

	var dates []string
	if err := ctx.ShouldBindJSON(&dates); err != nil {
		ucommon.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", fmt.Errorf("日期列表格式错误: %v", err))
		return
	}

	var allContents []map[string]interface{}

	for _, date := range dates {
		if len(date) != 8 {
			ucommon.Error(ctx, http.StatusBadRequest, "INVALID_DATE_FORMAT", fmt.Errorf("日期格式错误，应为YYYYMMDD格式: %s", date))
			return
		}
		parsedTime, err := time.Parse("20060102", date)
		if err != nil {
			ucommon.Error(ctx, http.StatusBadRequest, "INVALID_DATE", fmt.Errorf("无效的日期: %s", date))
			return
		}
		yearMonth := parsedTime.Format("2006-01")
		fileName := fmt.Sprintf("trades_%s.xlsx", parsedTime.Format("2006-01-02"))
		filePath := filepath.Join(basePath, yearMonth, fileName)

		if _, err := os.Stat(filePath); err != nil {
			if os.IsNotExist(err) {
				continue // 文件不存在跳过
			}
			ucommon.Error(ctx, http.StatusInternalServerError, "FILE_ACCESS_ERROR", fmt.Errorf("访问文件失败: %v", err))
			return
		}

		f, err := excelize.OpenFile(filePath)
		if err != nil {
			ucommon.Error(ctx, http.StatusInternalServerError, "EXCEL_READ_ERROR", fmt.Errorf("读取Excel失败: %v", err))
			return
		}
		sheetName := f.GetSheetName(0)
		rows, err := f.GetRows(sheetName)
		if err != nil {
			ucommon.Error(ctx, http.StatusInternalServerError, "EXCEL_READ_ERROR", fmt.Errorf("读取Excel内容失败: %v", err))
			return
		}
		if len(rows) == 0 {
			allContents = append(allContents, map[string]interface{}{
				"date":     date,
				"filename": fileName,
				"header":   []string{},
				"rows":     [][]string{},
			})
			continue
		}
		header := rows[0]
		var dataRows [][]string
		if len(rows) > 1 {
			dataRows = rows[1:]
		}
		allContents = append(allContents, map[string]interface{}{
			"date":     date,
			"filename": fileName,
			"header":   header,
			"rows":     dataRows,
		})
	}

	ucommon.Success(ctx, gin.H{
		"total_files": len(allContents),
		"files":       allContents,
	})
}

// FixBalanceAnomalies 修复余额异常
func (c *AdminController) FixBalanceAnomalies(ctx *gin.Context) {
	validator := common.NewBalanceValidator()

	// 修复余额问题
	if err := validator.FixBalanceIssues(); err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "fix_balance_issues_failed", err)
		return
	}

	ucommon.Success(ctx, gin.H{
		"message": "balance_anomalies_fixed_successfully",
	})
}

// CheckBalanceAnomalies 检查余额异常
func (c *AdminController) CheckBalanceAnomalies(ctx *gin.Context) {
	validator := common.NewBalanceValidator()

	// 检查余额完整性
	if err := validator.ValidateAllBalances(); err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "check_balance_anomalies_failed", err)
		return
	}

	ucommon.Success(ctx, gin.H{
		"message": "balance_anomalies_check_completed",
	})
}

// RunBalanceAudit 运行余额审计
func (c *AdminController) RunBalanceAudit(ctx *gin.Context) {
	validator := common.NewBalanceValidator()

	if err := validator.RunFullValidation(); err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "run_balance_audit_failed", err)
		return
	}

	ucommon.Success(ctx, gin.H{
		"message": "balance_audit_completed",
	})
}

// ==================== 数据看板相关接口 ====================

// GetTransactionDashboard 获取交易数据看板
func (c *AdminController) GetTransactionDashboard(ctx *gin.Context) {
	// 获取查询参数
	startDate := ctx.DefaultQuery("start_date", time.Now().AddDate(0, 0, -30).Format("2006-01-02"))
	endDate := ctx.DefaultQuery("end_date", time.Now().Format("2006-01-02"))

	// 创建交易统计服务
	statsService := service.NewTransactionStatsService()

	// 获取数据看板数据
	dashboard, err := statsService.GetDashboardData(ctx.Request.Context(), startDate, endDate)
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_dashboard_data_failed", err)
		return
	}

	ucommon.Success(ctx, dashboard)
}

// GetTransactionStats 获取交易统计数据列表
func (c *AdminController) GetTransactionStats(ctx *gin.Context) {
	// 获取查询参数
	query := models.TransactionStatsQuery{
		Month:     ctx.Query("month"),
		StartDate: ctx.Query("start_date"),
		EndDate:   ctx.Query("end_date"),
	}

	// 解析分页参数
	if limitStr := ctx.Query("limit"); limitStr != "" {
		if limit, err := strconv.ParseInt(limitStr, 10, 64); err == nil {
			query.Limit = limit
		}
	}
	if offsetStr := ctx.Query("offset"); offsetStr != "" {
		if offset, err := strconv.ParseInt(offsetStr, 10, 64); err == nil {
			query.Offset = offset
		}
	}

	// 创建交易统计服务
	statsService := service.NewTransactionStatsService()

	// 获取交易统计数据
	response, err := statsService.GetTransactionStats(ctx.Request.Context(), query)
	if err != nil {
		ucommon.Error(ctx, http.StatusInternalServerError, "get_transaction_stats_failed", err)
		return
	}

	ucommon.Success(ctx, response)
}

// GetTransactionStatsByMonth 根据月份获取交易统计数据
func (c *AdminController) GetTransactionStatsByMonth(ctx *gin.Context) {
	month := ctx.Param("month")
	if month == "" {
		ucommon.Error(ctx, http.StatusBadRequest, "month_required", fmt.Errorf("月份参数不能为空"))
		return
	}

	// 月份格式验证和转换
	// 支持多种格式：6, 06, 2025-6, 2025-06
	var formattedMonth string

	// 如果只是数字（如6），转换为当前年份-月份格式
	if len(month) <= 2 {
		// 尝试解析为月份数字
		if monthNum, err := strconv.Atoi(month); err == nil && monthNum >= 1 && monthNum <= 12 {
			// 使用当前年份
			currentYear := time.Now().Year()
			formattedMonth = fmt.Sprintf("%d-%02d", currentYear, monthNum)
		} else {
			ucommon.Error(ctx, http.StatusBadRequest, "invalid_month_format", fmt.Errorf("无效的月份格式: %s，应为1-12的数字", month))
			return
		}
	} else if len(month) == 7 && strings.Contains(month, "-") {
		// 已经是YYYY-MM格式
		formattedMonth = month
	} else {
		ucommon.Error(ctx, http.StatusBadRequest, "invalid_month_format", fmt.Errorf("无效的月份格式: %s，应为YYYY-MM格式或1-12的数字", month))
		return
	}

	// 创建交易统计服务
	statsService := service.NewTransactionStatsService()

	// 获取指定月份的统计数据
	stats, err := statsService.GetTransactionStatsByMonth(ctx.Request.Context(), formattedMonth)
	if err != nil {
		// 提供更详细的错误信息
		if strings.Contains(err.Error(), "no transaction stats found") {
			ucommon.Error(ctx, http.StatusNotFound, "transaction_stats_not_found",
				fmt.Errorf("未找到月份为 %s 的交易统计数据，请检查月份格式是否正确（应为YYYY-MM格式）", formattedMonth))
		} else {
			ucommon.Error(ctx, http.StatusInternalServerError, "get_transaction_stats_failed", err)
		}
		return
	}

	ucommon.Success(ctx, stats)
}

// GetTransactionStatsByYearMonth 根据年份和月份获取交易统计数据
func (c *AdminController) GetTransactionStatsByYearMonth(ctx *gin.Context) {
	yearStr := ctx.Param("year")
	monthStr := ctx.Param("month")

	if yearStr == "" || monthStr == "" {
		ucommon.Error(ctx, http.StatusBadRequest, "year_month_required", fmt.Errorf("年份和月份参数不能为空"))
		return
	}

	// 解析年份
	year, err := strconv.Atoi(yearStr)
	if err != nil || year < 2000 || year > 2100 {
		ucommon.Error(ctx, http.StatusBadRequest, "invalid_year", fmt.Errorf("无效的年份: %s，应为2000-2100之间的数字", yearStr))
		return
	}

	// 解析月份
	month, err := strconv.Atoi(monthStr)
	if err != nil || month < 1 || month > 12 {
		ucommon.Error(ctx, http.StatusBadRequest, "invalid_month", fmt.Errorf("无效的月份: %s，应为1-12之间的数字", monthStr))
		return
	}

	// 构建月份格式
	formattedMonth := fmt.Sprintf("%d-%02d", year, month)

	// 创建交易统计服务
	statsService := service.NewTransactionStatsService()

	// 获取指定年份和月份的统计数据
	stats, err := statsService.GetTransactionStatsByMonth(ctx.Request.Context(), formattedMonth)
	if err != nil {
		// 提供更详细的错误信息
		if strings.Contains(err.Error(), "no transaction stats found") {
			ucommon.Error(ctx, http.StatusNotFound, "transaction_stats_not_found",
				fmt.Errorf("未找到 %d年%d月 的交易统计数据", year, month))
		} else {
			ucommon.Error(ctx, http.StatusInternalServerError, "get_transaction_stats_failed", err)
		}
		return
	}

	ucommon.Success(ctx, stats)
}

// GetLatestTransactionStats 获取最新的交易统计数据
func (c *AdminController) GetLatestTransactionStats(ctx *gin.Context) {
	// 创建交易统计服务
	statsService := service.NewTransactionStatsService()

	// 获取最新的统计数据
	stats, err := statsService.GetLatestTransactionStats(ctx.Request.Context())
	if err != nil {
		ucommon.Error(ctx, http.StatusNotFound, "latest_transaction_stats_not_found", err)
		return
	}

	ucommon.Success(ctx, stats)
}

// GetTransactionStatsByID 根据ID获取交易统计数据
func (c *AdminController) GetTransactionStatsByID(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		ucommon.Error(ctx, http.StatusBadRequest, "id_required", fmt.Errorf("ID参数不能为空"))
		return
	}

	// 创建交易统计服务
	statsService := service.NewTransactionStatsService()

	// 获取指定ID的统计数据
	stats, err := statsService.GetTransactionStatsByID(ctx.Request.Context(), id)
	if err != nil {
		ucommon.Error(ctx, http.StatusNotFound, "transaction_stats_not_found", err)
		return
	}

	ucommon.Success(ctx, stats)
}

// GetPlatformSelectionConfig 获取平台选择配置
func (c *AdminController) GetPlatformSelectionConfig(ctx *gin.Context) {
	config := gin.H{
		"enabled":           config.GlobalConfig.PlatformSelection.Enabled,
		"monthly_platforms": config.GlobalConfig.PlatformSelection.MonthlyPlatforms,
		"default_platform":  config.GlobalConfig.PlatformSelection.DefaultPlatform,
		"current_month":     time.Now().Month(),
		"current_platform":  config.GetCurrentMonthPlatform(),
	}

	common.Success(ctx, config)
}

// UpdatePlatformSelectionConfig 更新平台选择配置
func (c *AdminController) UpdatePlatformSelectionConfig(ctx *gin.Context) {
	var req struct {
		Enabled          bool              `json:"enabled" binding:"required"`
		MonthlyPlatforms map[string]string `json:"monthly_platforms" binding:"required"`
		DefaultPlatform  string            `json:"default_platform" binding:"required,oneof=photonpay hlpay"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证月份平台映射
	for month, platform := range req.MonthlyPlatforms {
		monthNum, err := strconv.Atoi(month)
		if err != nil || monthNum < 1 || monthNum > 12 {
			common.Error(ctx, http.StatusBadRequest, "invalid_month", fmt.Errorf("invalid month: %s", month))
			return
		}
		if platform != "photonpay" && platform != "hlpay" {
			common.Error(ctx, http.StatusBadRequest, "invalid_platform", fmt.Errorf("invalid platform: %s", platform))
			return
		}
	}

	// 更新配置
	config.GlobalConfig.PlatformSelection.Enabled = req.Enabled
	config.GlobalConfig.PlatformSelection.MonthlyPlatforms = req.MonthlyPlatforms
	config.GlobalConfig.PlatformSelection.DefaultPlatform = req.DefaultPlatform

	// 这里可以添加配置持久化逻辑，比如保存到数据库或配置文件
	// 目前配置只在内存中，重启后会恢复默认值

	common.Success(ctx, gin.H{
		"message": "平台选择配置更新成功",
		"config": gin.H{
			"enabled":           req.Enabled,
			"monthly_platforms": req.MonthlyPlatforms,
			"default_platform":  req.DefaultPlatform,
			"current_month":     time.Now().Month(),
			"current_platform":  config.GetCurrentMonthPlatform(),
		},
	})
}
